﻿
function padNumber(num, len) {
    var padded = num.toString();
    while (padded.length < len)
        padded = "0" + padded;
    return padded;
}

function generateNames(prefix, suffix, startNum, endNum, pads) {
    var names = new Array();
    var end = endNum - startNum + 1;
    for (var i = 0; i < end; ++i)
        names[i] = prefix + padNumber(i + startNum, pads) + suffix;
    return names;
}

function parseName(name) {
    if (name.indexOf("$") > -1 && name.lastIndexOf("$") > name.indexOf("$")) {
        var i1 = name.indexOf("$");
        var i2 = name.lastIndexOf("$");
        var p = name.substring(i1, i2 + 1);
        var presuf = name.split(p);
        p = name.substring(i1 + 1, i2);
        var range = p.split("-");
        var n1 = parseInt(range[0], 10);
        var n2 = parseInt(range[1], 10);
        var pads = range[0].length;
        return generateNames(presuf[0], presuf[1], n1, n2, pads);
    }
    else if (name.indexOf("$") > -1 || name.indexOf("#") > -1 || name.indexOf("%") > -1) {
        throw "Invalid Name";
    }
    else {
        var names = new Array();
        names[0] = name;
        return names;
    }
}

//------------------------------------------------------------------


function check_vmName() {
    var text = document.getElementById("input_vmName").value;
    var names = parseName(text)
    document.getElementById("note_vmName").innerText = "(" + names.length + ")";
}

function check_hostName() {
    var text = document.getElementById("input_hostName").value;
    var names = parseName(text)
    document.getElementById("note_hostName").innerText = "(" + names.length + ")";
}


//------------------------------------------------------------------



// url : string
// callbk : int -> int -> string -> unit
function executeAjax(url, callbk) {
    if (!window.XMLHttpRequest) {
        alert("Unsupported browser");
        return;
    }
    var xmlhttp = new XMLHttpRequest();

    if (callbk) {
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4) {
                callbk(4, xmlhttp.status, xmlhttp.responseText);
            }
            else {
                callbk(xmlhttp.readyState);
            }
        };
    }

    xmlhttp.open("GET", url, true);
    xmlhttp.send(null);
}


function getRdp(vmGuid) {
    var url = "GetRdp.aspx?guid=" + vmGuid;
    var load = window.open(url, '', 'scrollbars=no,menubar=no,height=300,width=400,resizable=no,toolbar=no,location=no,status=no');
}

function buildCommands(vmState, vmGuid, vmName) {
    var start = "<a href=\"javascript:startVM('" + vmGuid + "','" + vmName + "');\"><img title=\"Start\" src=\"Images/PlayW.png\" style=\"border:none\" /></a>";
    var stop = "<a href=\"javascript:stopVM('" + vmGuid + "','" + vmName + "');\"><img title=\"Turn off\" src=\"Images/haltW.png\" style=\"border:none\" /></a>";
    var save = "<a href=\"javascript:saveVM('" + vmGuid + "','" + vmName + "');\"><img title=\"Suspend\" src=\"Images/StandByW.png\" style=\"border:none\" /></a>";
    var rdp = "<a href='javascript:getRdp(\"" + vmGuid + "\")'><img title=\"Connect...\" src=\"Images/MonitorW.png\" style=\"border:none\" /></a>";
    var deleteVm = "<a href=\"javascript:deleteVM('" + vmGuid + "','" + vmName + "');\"><img title=\"Delete\" src=\"Images/deleteW.png\" style=\"border:none\" /></a>";
    var deleteFailed = "<a href=\"javascript:cancelConfVM('" + vmGuid + "','" + vmName + "');\"><img title=\"Delete\" src=\"Images/deleteW.png\" style=\"border:none\" /></a>";
    var cancelConf = "<a href=\"javascript:cancelConfVM('" + vmGuid + "','" + vmName + "');\"><img title=\"Cancel\" src=\"Images/deleteW.png\" style=\"border:none\" /></a>";

    //var testMigrazione = "<a href=\"javascript:testMigrazione('" + vmGuid + "','" + vmName + "');\"><img title=\"Migration TEST\" src=\"Images/arrowW.png\" style=\"border:none\" /></a>";

    if (vmState == "Running") {
        return (stop + save + rdp);
    }
    else if (vmState == "Stopped" || vmState == "Suspended") {
        return (start + deleteVm);
    }
    else if (vmState == "Paused") {
        return (start);
    }
    else if (vmState == "Configuring") {
        return (cancelConf);
    }
    else if (vmState == "CreationFailed") {
        return (deleteFailed);
    }
    else return "&nbsp;";
}

function trim(arg) {
    var re = "/\s+$|^\s+/g";
    return arg.replace(re, "");
}

function buildVmTile(vmGuid, vmName, cpuCount, ramAmount, vmState) {
    var spanState = "";
    if (vmState)
        spanState = "  <span id='" + vmGuid + ".state' class=\"VMState\">"+ vmState +"</span>";
    else
        spanState = "  <span id='" + vmGuid + ".state' class=\"VMState unknown\">Unknown state</span>";

    var ajaxScript = "invokeGetVmStatus('" + vmGuid + "', '" + vmName + "');\r\n";
    var refreshBtn = "<a href=\"javascript:" + ajaxScript + "\"><img title=\"Update machine state and thumbnail\" src=\"Images/refreshW.png\" style=\"border:none\" /></a>";
    var tableRowTemplate =
        "<div class=\"VMInfo\">" +
        "  <div class=\"VMName\">" + vmName + "</div>" +
        "  <div class=\"VMData\">" +
        "  <div class=\"VMThumbnail\">" +
        "    <a href='GetThumbnail.aspx?guid=" + vmGuid + "&width=1024'>" +
        "      <img id='" + vmGuid + ".thumb' title=\"" + cpuCount + "core " + ramAmount + "Mb\" style='border:none; width:100; height:75' src='GetThumbnail.aspx?guid=" + vmGuid + "&width=100' alt='VM Thumbnail' />" +
        "    </a>" +
        "  </div>" +
        spanState +
        "  <div class=\"VMParamInfo\">" +
        "    <span class=\"VMRefreshStatus\">" + refreshBtn + "</span>" +
        "    </div>" +
        "    <div id='" + vmGuid + ".cmds' class=\"VMToolbar\">&nbsp;</div></div>" +
        "</div>";
    return tableRowTemplate;
}



function invokeCreateNewVm(numVm, vmName, hostName, adminPass, cpuCores, ramAmount, templateId) {
    var callbk = function(readyState, status, responseText) {
        if (readyState == 4) {
            if (status == 200) {
                // var vmGuid = responseText;
                // document.getElementById("VirtualMachines").innerHTML += buildVmTile(vmGuid, vmName, cpuCores, ramAmount, "...");
                // var code = "invokeGetVmStatus(\"" + vmGuid + "\", \"" + vmName + "\")";
                // setInterval(code, 30000);
                // setTimeout(code, 2000);
            }
            else {
                alert("error " + status + ": " + responseText);
            }
        }
    };

    var params =
          "numVm=" + numVm +
          "&vmName=" + vmName +
          "&hostName=" + hostName +
          "&adminPass=" + adminPass +
          "&cpuCores=" + cpuCores +
          "&ramAmount=" + ramAmount +
          "&templateId=" + templateId;
    var url = "GetAjax.aspx?func=createNewVm&" + params;

    executeAjax(url, callbk);
}



function createNewVm() {
    var cpuCores = document.getElementById("input_cpuCores").value;
    var ramAmount = document.getElementById("input_ramAmount").value;
    var adminPass = document.getElementById("input_adminPass").value;
    if (trim(cpuCores) == "" || trim(ramAmount) == "" || trim(adminPass) == "") {
        alert("Values error");
        return;
    }

    var templateId = document.getElementById("vmTemplate_Id").value;
    if (trim(templateId) == "") {
        alert("templateId error");
        return;
    }

    var numNames = parseName(document.getElementById("input_vmName").value).length;
    var numHostnames = parseName(document.getElementById("input_hostName").value).length;
    if (numNames != numHostnames) {
        alert("# of VmNames do not match # of HostNames");
        return;
    }

    var vmnames = document.getElementById("input_vmName").value;
    var hostnames = document.getElementById("input_hostName").value;
    invokeCreateNewVm(numNames, vmnames, hostnames, adminPass, cpuCores, ramAmount, templateId);

    OctopusHideNewVM(document.getElementById("CancelNewVM"));
}


function invokeGetVmStatus(guid, vmName) {
    var oldState = document.getElementById(guid + ".state").innerHTML;
    if (oldState == "Deleted")
        return;

    var callbk = function(readyState, status, responseText) {
        if (readyState == 4) {
            if (status == 200 || oldState == "Deleting") {
                var state = (status == 200) ? responseText : "Deleted";
                var cmds = buildCommands(state, guid, vmName);

                // name patch
                if (state == "ScheduledForCreation") state = "Scheduled";

                document.getElementById(guid + ".state").className = 'VMState';
                document.getElementById(guid + ".state").innerHTML = state;
                document.getElementById(guid + ".cmds").innerHTML = cmds;

                switch (state)
                {
                    case "Running":
                    case "Configuring": refreshVmImage(guid); break;
                }
            }
            else {
                document.getElementById(guid + ".state").className = 'VMState unknown';
                document.getElementById(guid + ".state").innerHTML = "Error code " + status;
                document.getElementById(guid + ".cmds").innerHTML = "";
            }
        }
    };

    document.getElementById(guid + ".state").className = 'VMState refreshing';

    var url = "GetAjax.aspx?func=getVmStatus&guid=" + guid;
    executeAjax(url, callbk);
}

function invokeGetUserMessages() {
    var callbk = function(readyState, status, responseText) {
        if (readyState == 4) {
            if (status == 200) {
                document.getElementById("divMessages").innerHTML = responseText;
            }
            else {
                document.getElementById("divMessages").innerHTML = "Ajax Error";
            }
        }
    };

    var url = "GetAjax.aspx?func=getUserMessages";
    executeAjax(url, callbk);
}

function refreshVmImage(guid) {
    var imgId = guid + ".thumb";
    var time = new Date().getTime();
    document.getElementById(imgId).src = "GetThumbnail.aspx?guid=" + guid + "&width=100&dummy=" + time;
}

// cancellami appena non servo piu'
function testMigrazione(guid, name) {
    var conf = confirm("Vuoi migrare questa VM in un host random?");
    if (conf) {
        document.getElementById(guid + ".state").innerHTML = "Migrating";
        document.getElementById(guid + ".cmds").innerHTML = "&nbsp;";
        var url = "GetAjax.aspx?func=testMigrationVm&guid=" + guid;
        executeAjax(url, null);
    }
}

function deleteVM(guid, name) {
    var conf = confirm("Are you sure you want to remove " + name + " ?");
    if (conf) {
        document.getElementById(guid + ".state").innerHTML = "Deleting";
        document.getElementById(guid + ".cmds").innerHTML = "&nbsp;";
        var url = "GetAjax.aspx?func=deleteVm&guid=" + guid;
        executeAjax(url, null);
    }
}
function cancelConfVM(guid, name) {
    var conf = confirm("Are you sure you want to cancel the creation of " + name + " ?");
    if (conf) {
        document.getElementById(guid + ".state").innerHTML = "Deleting";
        document.getElementById(guid + ".cmds").innerHTML = "&nbsp;";
        var url = "GetAjax.aspx?func=cancelConfVm&guid=" + guid;
        executeAjax(url, null);
    }
}
function startVM(guid, name) {
    document.getElementById(guid + ".state").innerHTML = "Starting";
    document.getElementById(guid + ".cmds").innerHTML = "&nbsp;";
    var url = "GetAjax.aspx?func=startVm&guid=" + guid;
    executeAjax(url, null);
}
function stopVM(guid, name) {
    var conf = confirm("Are you sure you want to turn off " + name + " ?");
    if (conf) {
        document.getElementById(guid + ".state").innerHTML = "Stopping";
        document.getElementById(guid + ".cmds").innerHTML = "&nbsp;";
        var url = "GetAjax.aspx?func=stopVm&guid=" + guid;
        executeAjax(url, null);
    }
}
function saveVM(guid, name) {
    document.getElementById(guid + ".state").innerHTML = "Saving";
    document.getElementById(guid + ".cmds").innerHTML = "&nbsp;";
    var url = "GetAjax.aspx?func=saveVm&guid=" + guid;
    executeAjax(url, null);
}

function vmTemplatesChanged(obj) {
    var title = obj[obj.selectedIndex].title;
    document.getElementById("vmTemplate_Descr").innerHTML = title + "<br/>";
    document.getElementById("vmTemplate_Id").value = obj.value;
}


//---
//--------------------------------------------------
//-----


AnimeJInterp.iv = function(time, tstep, obj, prop, fromOrSteps, to) {
    if (typeof (fromOrSteps) == 'number')
        fromOrSteps = [{ t: 0.0, v: fromOrSteps }, { t: 1.0, v: to}];
    return new AnimeJInterpolatedTask(new AnimeJLinearInterpolator(obj, prop, fromOrSteps, AnimeJConv.Int, '', ''), time, tstep);
};


function OctopusApplyTileStyle() {
    var a = getElementsByClass('VMState', 'span'), i;
    for (i = 0; i < a.length; i++)
        AnimeSetOpacity(a[i], 0.5);

    var msg = document.getElementById('divMessages');
    if (msg) {
        var moveFwd = null;

        var moveBk = function() {
            var t = new Timeline();
            t.SetAt(0, AnimeJInterp.iv(20000, 100, msg, 'scrollTop', parseInt(msg.scrollHeight) - 100, 0));
            t.OnEnd = moveFwd;
            t.Run();
        }

        moveFwd = function() {
            var t = new Timeline();
            t.SetAt(0, AnimeJInterp.iv(20000, 100, msg, 'scrollTop', 0, parseInt(msg.scrollHeight) - 100));
            t.OnEnd = moveBk;
            t.Run();
        };

        moveFwd();
    }
}


function OctopusNewVM() {
    var newvm = document.getElementById('NewVM');
    var content = document.getElementById('ContentTiles');
    newvm.style.position = 'absolute';
    newvm.style.top = content.offsetTop;
    newvm.style.left = document.body.clientWidth + 20;
    newvm.style.display = 'block';

    content.style.left = content.offsetLeft;
    content.style.top = content.offsetTop;
    content.style.width = content.offsetWidth;
    content.style.position = 'absolute';

    var cbx = parseInt(content.style.left);
    var cex = -parseInt(content.offsetWidth) - 10;
    var nbx = parseInt(newvm.style.left);
    var nex = cbx + 50;

    var banner = document.getElementById('Banner');
    var bbx = parseInt(banner.style.left);
    var bex = bbx + (cex - cbx);

    var bgbx = 0;
    var bgex = (cex - cbx);

    var t = new Timeline();
    t.SetAt(0, AnimeJInterp.px(500, 30, content.style, 'left', cbx, cex));
    t.SetAt(0, AnimeJInterp.px(500, 30, newvm.style, 'left', nbx, nex));
    t.SetAt(0, AnimeJInterp.px(500, 30, banner.style, 'left', bbx, bex));
    t.SetAt(0, AnimeJInterp.px(500, 30, document.body.style, 'backgroundPosition', bgbx, bgex));
    t.Run();

    var rt = new Timeline();
    rt.SetAt(0, AnimeJInterp.px(500, 30, content.style, 'left', cex, cbx));
    rt.SetAt(0, AnimeJInterp.px(500, 30, newvm.style, 'left', nex, nbx));
    rt.SetAt(0, AnimeJInterp.px(500, 30, banner.style, 'left', bex, bbx));
    rt.SetAt(0, AnimeJInterp.px(500, 30, document.body.style, 'backgroundPosition', bgex, bgbx));
    rt.OnEnd = function(d) {
        newvm.style.display = 'none';
        content.style.position = '';
        content.style.width = 'auto';
    };

    document.getElementById('CancelNewVM').CancelAnimation = rt;
}

function OctopusHideNewVM(obj) {
    if (obj.CancelAnimation) {
        obj.CancelAnimation.Run();
    }
    else {
        var newvm = document.getElementById('NewVM');
        var content = document.getElementById('ContentTiles');
        var banner = document.getElementById('Banner');

        var bgbx = 0;
        var cbx = 108;
        var bbx = 250;
        var nbx = 818;

        var cex = parseInt(content.style.left);
        var nex = parseInt(newvm.style.left);
        var bex = parseInt(banner.style.left);
        var bgex = (cex - cbx);

        var rt = new Timeline();
        rt.SetAt(0, AnimeJInterp.px(500, 30, content.style, 'left', cex, cbx));
        rt.SetAt(0, AnimeJInterp.px(500, 30, newvm.style, 'left', nex, nbx));
        rt.SetAt(0, AnimeJInterp.px(500, 30, banner.style, 'left', bex, bbx));
        rt.SetAt(0, AnimeJInterp.px(500, 30, document.body.style, 'backgroundPosition', bgex, bgbx));
        rt.OnEnd = function(d) {
            newvm.style.display = 'none';
            content.style.position = '';
            content.style.width = 'auto';
        };
        rt.Run();
    }
}



//---
//--------------------------------------------------
//-----


function DisplayTileTask(tile) {
    this.OnPause = function() { };
    this.OnResume = function() { };
    this.OnStop = function() { };
    this.DoAction = function(delay) {
        document.getElementById("VirtualMachines").innerHTML += tile;
    }
}

function ApplyVmTileStyleTask(vmGuid, vmState, vmName) {
    this.OnPause = function() { };
    this.OnResume = function() { };
    this.OnStop = function() { };
    this.DoAction = function(delay) {
        var id = vmGuid + ".state";
        var div = document.getElementById(id);
        AnimeSetOpacity(div, 0.5);

        var cmds = buildCommands(vmState, vmGuid, vmName);
        document.getElementById(vmGuid + ".cmds").innerHTML = cmds;
    }
}
